<?php

namespace app\admin\controller;
use app\common\model\AutoreplyModel;
use think\Db;
class Weixin extends Base
{
   //微信回复设置
    public function autoreply(){
        $result=db('weixin_autoreply')->order('id asc')->select();
        $this->assign('list',$result);
        return $this->fetch();
    }
    public function autoreplydel($id){
        db('weixin_autoreply')->where(['pid'=>$id])->delete();
        if(db('weixin_autoreply')->delete($id)){
            return json(['code' => 1, 'data' => '', 'msg' => '删除成功']);
        }else{
            return json(['code' =>0, 'data' => '', 'msg' => '删除失败']);
        }
    }
    public function autoreplyeditor($id){

        if($this->request->isAjax()){
            $data=$this->request->post();
            $model=new AutoreplyModel();
            if($model->update($data)){
                return json(['code' => 1, 'data' => '', 'msg' => '更新成功']);
            }else{
                return json(['code' =>0, 'data' => '', 'msg' => '更新失败']);
            }
        }

        $result=db('weixin_autoreply')->find($id);
        $this->assign('data',$result);
        return $this->fetch();

    }

    public function autoreplyadd(){
        if($this->request->isAjax()){
            $post=$this->request->post();
            $model=new AutoreplyModel();
            if($model->save($post)){
                return json(['code' => 1, 'data' => '', 'msg' => '添加成功']);
            }else{
                return json(['code' =>0, 'data' => '', 'msg' => '添加失败']);
            }

        }

        return $this->fetch();
    }

    public function  status()
    {
        $id=input('param.id');
        $status = Db::name('weixin_autoreply')->where(array('id'=>$id))->value('status');//判断当前状态情况
        if($status==1)
        {
            $flag = Db::name('weixin_autoreply')->where(array('id'=>$id))->setField(['status'=>0]);
            return json(['code' => 1, 'data' => $flag['data'], 'msg' => '已禁止']);
        }
        else
        {
            $flag = Db::name('weixin_autoreply')->where(array('id'=>$id))->setField(['status'=>1]);
            return json(['code' => 0, 'data' => $flag['data'], 'msg' => '已开启']);
        }
    }

    public function menu(){
        $list=db('weixin_menu')->order('sort asc')->select();

        $result = array();
        if (is_array($list)) {
            foreach ($list as $vo) {
                if ($vo['pid'] == 0) {
                    $vo['val'] = ($vo['type'] == 'click') ? $vo['key'] : $vo['url'];
                    $sub_button = array();
                    foreach ($list as $val) {
                        $val['val'] = ($val['type'] == 'click') ? $val['key'] : $val['url'];
                        if ($val['pid'] == $vo['id']) {
                            $sub_button[] = $val;
                        }
                    }
                    $vo['sub_button'] = $sub_button;
                    $result[] = $vo;
                }
            }
        }

        $this->assign('list', $result);
        return $this->fetch();
    }
    public function menuadd(){
        if($this->request->isAjax()){
            $post=$this->request->post();
            $data=$post['data'];
            array_walk($data, function($val,$key) use(&$data){
                $data[$key]=trim($val,' ');
            });
            if(db('weixin_menu')->insert($data)){
                return json(['code' => 1, 'data' => '', 'msg' => '添加成功']);
            }else{
                return json(['code' =>0, 'data' => '', 'msg' => '添加失败']);
            }
        }
    }
    public function menuedit($id){
        if($this->request->isGet()){
            if($data=db('weixin_menu')->find($id)){
                return json(['code' => 1, 'data' => $data, 'msg' => '']);
            }else{
                return json(['code' =>0, 'data' => '', 'msg' => '']);
            }
        }
        if($this->request->isPost()){
            $post=$this->request->post();
            $data=$post['data'];
            array_walk($data, function($val,$key) use(&$data){
                $data[$key]=trim($val,' ');
            });
            $data['status']=isset($data['status'])?$data['status']:0;
            if(db('weixin_menu')->where(['id'=>$id])->update($data)){
                return json(['code' => 1, 'data' => '', 'msg' => '修改成功']);
            }else{
                return json(['code' =>0, 'data' => '', 'msg' => '修改失败']);
            }
        }
    }
    public function menudel($id){
        if( db('weixin_menu')->delete(['id'=>$id])){
            return json(['code' => 1, 'data' => '', 'msg' => '添加成功']);
        }else{
            return json(['code' =>0, 'data' => '', 'msg' => '添加失败']);
        }
    }
    public function menugenerate(){
        $list=db('weixin_menu')->where(['status'=>1])->order('sort asc')->select();

        if (empty($list)) {
            return json(['code' =>0, 'data' => '', 'msg' => '请至少添加一个自定义菜单']);
        }
        $data = array();
        if (is_array($list)) {
            foreach ($list as $val) {
                if ($val['pid'] == 0) {
                    $sub_button = array();
                    foreach ($list as $v) {
                        if ($v['pid'] == $val['id']) {
                            $sub_button[] = $v;
                        }
                    }
                    $val['sub_button'] = $sub_button;
                    $data[] = $val;
                }
            }
        }
        $menu_list = array();
        foreach ($data as $key => $val) {
            if (empty($val['sub_button'])) {
                $menu_list['button'][$key]['type'] = $val['type'];
                $menu_list['button'][$key]['name'] = $val['name'];
                if ('click' == $val['type']) {
                    $menu_list['button'][$key]['key'] = $val['key'];
                } else {
                    $menu_list['button'][$key]['url'] = htmlspecialchars_decode($val['url']);
                }
            } else {
                $menu_list['button'][$key]['name'] = $val['name'];
                foreach ($val['sub_button'] as $k => $v) {
                    $menu_list['button'][$key]['sub_button'][$k]['type'] = $v['type'];
                    $menu_list['button'][$key]['sub_button'][$k]['name'] = $v['name'];
                    if ('click' == $v['type']) {
                        $menu_list['button'][$key]['sub_button'][$k]['key'] = $v['key'];
                    } else {
                        $menu_list['button'][$key]['sub_button'][$k]['url'] = htmlspecialchars_decode($v['url']);
                    }
                }
            }
        }
        /*
         * $data = array( 'button'=>array( array('type'=>'click', 'name'=>"今日歌曲", 'key'=>'MENU_KEY_MUSIC'), array('type'=>'view', 'name'=>"歌手简介", 'url'=>'http://www.qq.com/'), array('name'=>"菜单", 'sub_button'=>array(array('type'=>'click', 'name'=>'hello world', 'key'=>'MENU_KEY_MENU'))) ) );
         */
        $WechatMenu=new \Wechat\WechatMenu([
            'token'             => config('wx_token'), // 填写你设定的key
            'appid'             => config('wx_appid'), // 填写高级调用功能的app id, 请在微信开发模式后台查询
            'appsecret'         => config('wx_appsecret'), // 填写高级调用功能的密钥
            'encodingaeskey'    => config('wx_encodingaeskey'), // 填写加密用的EncodingAESKey（可选，接口传输选择加密时必需）
            'mch_id'            => config('wx_mch_id'), // 微信支付，商户ID（可选）
            'partnerkey'        => config('wx_partnerkey'), // 微信支付，密钥（可选）
            'ssl_cer'           =>  config('wx_ssl_cer'), // 微信支付，证书cert的路径（可选，操作退款或打款时必需）
            'ssl_key'           =>  config('wx_ssl_key'), // 微信支付，证书key的路径（可选，操作退款或打款时必需）
        //    'cachepath'         => config('wx_appid'), // 设置SDK缓存目录（可选，默认位置在./src/Cache下，请保证写权限）
        ]);

      //  pe($WechatMenu->deleteMenu());
       // pe(preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function('$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'), json_encode($menu_list)));
        $str=' {
     "button":[     
      {
           "name":"信息上报",
           "sub_button":[
           {	
               "type":"view",
               "name":"商家登记",
               "url":"http://qiyu.zhiluw.com/index.php/admin/index/index.html"
            }
            ]
       }]
 }';
       // pe($menu_list);
       // pe(json_decode($str,true));
        if ($WechatMenu->createMenu($menu_list)) {
            return json(['code' =>1, 'data' => '', 'msg' => '创建成功，等待生效']);

        }else{
            return json(['code' =>0, 'data' => '', 'msg' => '创建失败!错误代码'.$WechatMenu->errCode.'错误提示'.$WechatMenu->errMsg]);
        }

    }

}